<template>
  <Dialog
    v-model="show"
    :title="props.data?.id ? t('discountActivity.editTitle') : t('discountActivity.addTitle')"
    width="800px"
    @close="close"
    @confirm="handleSubmit"
  >
    <div class="h-600 overflow-y-auto">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="200px"
      >
        <el-form-item :label="t('discountActivity.activityName')" prop="name">
          <el-input v-model="formData.name" :placeholder="t('discountActivity.activityNamePlaceholder')" />
        </el-form-item>

        <el-form-item :label="t('discountActivity.selectProduct')" prop="products">
          <div class="d-flex align-items-center">
            <el-button type="primary" @click="openProductDialog"
              >{{ t('discountActivity.selectProduct') }}</el-button
            >
            <span v-if="formData.products.length" class="ml-2">
              {{ t('discountActivity.selectedProductsCount', { count: formData.products.length }) }}
            </span>
          </div>
        </el-form-item>

        <el-table
          class="mb12"
          :data="formData.products"
          row-key="id"
          height="300"
          v-if="formData.products.length"
        >
          <el-table-column :label="t('discountActivity.productImage')" width="100">
            <template #default="{ row }">
              <el-image :src="row.image" style="width: 50px; height: 50px" />
            </template>
          </el-table-column>
          <el-table-column :label="t('discountActivity.productName')" :prop="'name' + locale" />
          <el-table-column :label="t('discountActivity.productPriceUnit')" prop="minPrice" />
          <el-table-column :label="t('discountActivity.shopName')" :prop="'tenantName' + locale" />
          <el-table-column :label="t('discountActivity.operation')" width="100" fixed="right">
            <template #default="{ row }">
              <el-button type="text" @click="handleDelete(row)">{{ t('discountActivity.delete') }}</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item :label="t('discountActivity.discount')" prop="discountRate">
          <el-input-number
            v-model="formData.discountRate"
            :min="0"
            :max="100"
            :precision="0"
            :step="1"
          />
        </el-form-item>

        <el-form-item :label="t('discountActivity.activityTime')" prop="activityTime">
          <el-date-picker
            v-model="formData.activityTime"
            type="datetimerange"
            :range-separator="t('discountActivity.to')"
            :start-placeholder="t('discountActivity.startDate')"
            :end-placeholder="t('discountActivity.endDate')"
          />
        </el-form-item>
      </el-form>
    </div>
  </Dialog>

  <!-- 选择商品弹窗 -->
  <Dialog
    v-model="productDialogVisible"
    :title="t('discountActivity.selectProductTitle')"
    width="800px"
    @confirm="confirmProducts"
  >
    <div class="mb-3 flex_aic_jcsb">
      <el-input
        v-model="productSearchKey"
        :placeholder="t('discountActivity.productNamePlaceholder')"
        style="width: 300px"
        clearable
      />
      <el-button type="primary" @click="handleProductSearch">{{ t('discountActivity.searchProduct') }}</el-button>
    </div>

    <el-table
      :data="productList"
      @selection-change="handleSelectionChange"
      row-key="id"
      ref="multipleTableRef"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" :label="t('discountActivity.serial')" width="60" />
      <el-table-column :label="t('discountActivity.productImage')" width="100">
        <template #default="{ row }">
          <el-image :src="row.image" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column :prop="'name' + locale" :label="t('discountActivity.productName')" />
      <el-table-column prop="minPrice" :label="t('discountActivity.productPrice')" />
      <el-table-column :prop="'tenantName' + locale" :label="t('discountActivity.shopName')" />
    </el-table>
    <div class="mt12 flex_aic_jcc">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
      />
    </div>
  </Dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import moment from "moment";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

const { t, locale } = useI18n();

const multipleTableRef = ref(null);
const show = defineModel();
const emit = defineEmits(["success"]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);
const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
});

// 表单数据
const formData = ref({
  name: "",
  products: [],
  discountRate: "",
  activityTime: [],
});

// 表单校验规则
const rules = {
  name: [{ required: true, message: t('discountActivity.activityNameRequired'), trigger: "blur" }],
  products: [{ required: true, message: t('discountActivity.productsRequired'), trigger: "change" }],
  discountRate: [{ required: true, message: t('discountActivity.discountRequired'), trigger: "change" }],
  activityTime: [
    { required: true, message: t('discountActivity.activityTimeRequired'), trigger: "change" },
  ],
};

// 店铺选项
const shopOptions = ref([]);
// 商品弹窗相关
const productDialogVisible = ref(false);
const productSearchKey = ref("");
const productList = ref([]);
const selectedProducts = ref([]);

const getDetail = () => {
  Api.skuActivity_detail(props.data.id).then((res) => {
    if (res.status === 200) {
      formData.value = {
        ...res.data,
        products: res.data.skus,
        activityTime: [moment(res.data.startTime), moment(res.data.endTime)],
      };
    }
  });
};

watch(show, (val) => {
  if (val && props.data?.id) {
    getDetail();
  }
});

const formRef = ref();

// 打开商品选择弹窗
const openProductDialog = () => {
  currentPage.value = 1;
  getProductList();
  productDialogVisible.value = true;
  // TODO: 加载商品列表
};

// 处理商品搜索
const handleProductSearch = () => {
  currentPage.value = 1;
  getProductList();
};

// 处理商品选择
const handleSelectionChange = (selection) => {
  selectedProducts.value = selection;
};

// 确认选择商品
const confirmProducts = () => {
  formData.value.products = selectedProducts.value;
  productDialogVisible.value = false;
};

const handleSubmit = () => {
  const user = Storage.get("user", true)
  formRef.value.validate((valid) => {
    if (valid) {
      const submitData = {
        name: formData.value.name,
        tenantId: user.tenant.id,
        skus: selectedProducts.value.map((v) => ({ id: v.id })),
        discountRate: formData.value.discountRate,
        startTime: moment(formData.value.activityTime[0]).valueOf(),
        endTime: moment(formData.value.activityTime[1]).valueOf(),
      };
      Api.skuActivity_add(submitData).then((res) => {
        if (res.status === 200) {
          ElMessage.success(t('discountActivity.operationSuccess'));
          emit("success", submitData);
          close();
        }
      });
    }
  });
};

const close = () => {
  formData.value = {
    name: "",
    products: [],
    discountRate: "",
    activityTime: [],
  };
  show.value = false;
  formRef.value.resetFields();
};

// 获取商品列表
const getProductList = () => {
  Api.sku_list({
    page: currentPage.value - 1,
    size: pageSize.value,
    ['name' + locale.value]: productSearchKey.value,
    status: 1,
  }).then((res) => {
    productList.value = res.data.content || [];
    total.value = +res.data.totalElements || 0;
    nextTick(() => {
      const rows = productList.value?.filter((v) =>
        formData.value.products.find((v2) => v2.id === v.id)
      );
      rows.forEach((row) => {
        multipleTableRef.value?.toggleRowSelection(row);
      });
    });
  });
};

// 删除商品
const handleDelete = (row) => {
  formData.value.products = formData.value.products.filter(
    (v) => v.id !== row.id
  );
};
</script>

<style lang="scss" scoped>
.h-600 {
  height: 600px;
}
.lht-38 {
  line-height: 38px;
}
.w-120 {
  width: 120px;
}
.mt24 {
  margin-top: 24px;
}
</style>
